<?php
/**
 * @user:andy
 * @date:2021/6/14
 * @company:http://www.sjdphp.com
 * @desc: 校验登陆(中间件)
 */

namespace app\common\middleware;


use app\common\model\Back as BackModel;
use app\common\server\Json;
use app\common\server\SystemLog;
use app\common\model\BackLog as BackLogModel;
use app\common\server\Tools;
use think\facade\Cookie;

class CheckAdminToken
{
    public function handle($request,\Closure $next){

        ## 接受参数
        $token = Cookie::get(config("project.back_cookie.cookie_name"));
        ## 校验参数是否合法
        if(empty($token)){
            return redirect("/back/login/signIn");
        }
        ## 查询管理员登陆表
        try{
            $backLogInfo = BackLogModel::where(array("login_token" => $token,'log_status' => 0))
                        ->hidden(['back_log_id','login_token','log_status','create_time','update_time'])
                        ->find();
        }catch(\Exception $e){
            SystemLog::insertLog("\app\common\middleware\CheckAdminToken:32",$e->getMessage());
        }

        if(empty($backLogInfo)){
            return redirect("/back/login/signIn");
        }

        ## 判断cookie的过期时间
        if($backLogInfo["end_time"] <= time()){
            ## 清除cookie
            Cookie::delete(config("project.back_cookie.cookie_name"));
            ## 修改登陆表数据
            $backLogInfo->log_status = 1;
            $backLogInfo->save();
            ## 跳转登陆页
            return redirect("/back/login/signIn");
        }

        ## 获取管理员信息
        try{
            $backInfo = BackModel::where(array("back_id" => $backLogInfo["back_id"],'back_status' => config("project.mysql_code.table_normal")))
                        ->field("back_id,back_name,role_id")->find();
        }catch(\Exception $e){
            SystemLog::insertLog("\app\common\middleware\CheckAdminToken:45",$e->getMessage());
        }

        if(empty($backInfo)) redirect("/back/login/signIn");

        ## 将管理员数据存入request
        $request->BackInfo = $backInfo->toArray();

        ## 向下执行
        return $next($request);
    }
}